<?php
################################################################################################
#	DIY Module Builder for Opencart 1.5.1.x From HostJars http://opencart.hostjars.com			 #
################################################################################################
class ModelModuleTFilter extends Model {

	public function eleminateFilters($f_list=false)
	{
		if(!$f_list)
		{
			return;
		}
		$fids=implode(",",$f_list);
		$q="DELETE FROM `".DB_PREFIX."tfm_filter` WHERE `filter_id` NOT IN ({$fids})";
		$this->db->query($q);
		$q="DELETE FROM `".DB_PREFIX."tfm_filter_item` WHERE `filter_id` NOT IN ({$fids})";
		$this->db->query($q);
	}
	public function cleanFilter($filter_id, $iids=false)
	{
		if(!$filter_id || !$iids)
		{
			return;
		}
		$iids=implode(",",$iids);
		$q="DELETE FROM `".DB_PREFIX."tfm_filter_item` WHERE `filter_id`='{$filter_id}' AND `filter_item_id` NOT IN ({$iids})";
		$this->db->query($q);
	}
	
	public function updateFilter($filter_id,&$filter)
	{
		$filter["instock"]=(isset($filter["instock"]))?implode(",",$filter["instock"]):'';
		$filter["range_id"]=(isset($filter["range_id"]))?$filter["range_id"]:'';
		$db_prefix=DB_PREFIX;
		$q=<<<SQL
		UPDATE `{$db_prefix}tfm_filter` SET
		`name`='{$filter["name"]}',
		`range_type`='{$filter["range_type"]}',
		`range_id`='{$filter["range_id"]}',
		`instock`='{$filter["instock"]}',
		`sort_order`='{$filter["sort_order"]}'
		WHERE `filter_id`='{$filter_id}'
SQL;
		$this->db->query($q);
		$filter["filter_id"]=$filter_id;
	}
	
	public function insertFilter(&$filter)
	{
		$filter["instock"]=(isset($filter["instock"]))?implode(",",$filter["instock"]):'';
		$filter["range_id"]=(isset($filter["range_id"]))?$filter["range_id"]:'';
		$db_prefix=DB_PREFIX;
		$q=<<<SQL
		INSERT INTO `{$db_prefix}tfm_filter` VALUE
		(
			'',
			'{$filter["name"]}',
			'{$filter["range_type"]}',
			'{$filter["range_id"]}',
			'{$filter["instock"]}',
			'{$filter["sort_order"]}'
		)
SQL;
		$this->db->query($q);
		$filter["filter_id"]=$this->db->getLastId();
		return $filter["filter_id"];
	}
	
	public function updateItem($item_id,$item)
	{
		self::serializeRange($item["range"]);
		$db_prefix=DB_PREFIX;
		$q=<<<SQL
		UPDATE `{$db_prefix}tfm_filter_item` SET
		`filter_id`='{$item["filter_id"]}',
		`title`='{$item["title"]}',
		`item_type`='{$item["item_type"]}',
		`item_id`='{$item["item_id"]}',
		`product_field`='{$item["product_field"]}',
		`multiple`='{$item["multiple"]}',
		`display`='{$item["display"]}',
		`range`='{$item["range"]}',
		`sort_order`='{$item["sort_order"]}'
		WHERE `filter_item_id`='{$item_id}'
SQL;
		$this->db->query($q);
	}
	
	
	
	public function insertItem($item)
	{
		self::serializeRange($item["range"]);
		$db_prefix=DB_PREFIX;
		$q=<<<SQL
		INSERT INTO `{$db_prefix}tfm_filter_item` VALUE
		(
		'',
		'{$item["filter_id"]}',
		'{$item["title"]}',
		'{$item["item_type"]}',
		'{$item["item_id"]}',
		'{$item["product_field"]}',
		'{$item["multiple"]}',
		'{$item["display"]}',
		'{$item["range"]}',
		'{$item["sort_order"]}'
		)
SQL;
		$this->db->query($q);
		return $this->db->getLastId();
	}
	
	private static function serializeRange(&$range)
	{
		foreach($range as $key=>$range_item)
		{
			$range[$key]=implode(":",$range_item);
		}
		$range=implode(",",$range);
	}

	public function createModuleTables() {
		$db_prefix=DB_PREFIX;
		$q=<<<SQL
		CREATE VIEW `{$db_prefix}tfm_attribute` AS SELECT a.*,ad.language_id,ad.name, (SELECT agd.name FROM {$db_prefix}attribute_group_description agd WHERE agd.attribute_group_id = a.attribute_group_id AND agd.language_id = ad.language_id) AS attribute_group FROM {$db_prefix}attribute a LEFT JOIN {$db_prefix}attribute_description ad ON (a.attribute_id = ad.attribute_id)
SQL;
		$this->db->query($q);
		
		$q=<<<SQL
		CREATE TABLE `{$db_prefix}tfm_filter` (
		`filter_id` int(3) NOT NULL AUTO_INCREMENT,
		`name` text NOT NULL,
		`range_type` enum('a','ag','c','m') DEFAULT NULL,
		`range_id` int(11) DEFAULT NULL,
		`instock` text NOT NULL,
		`sort_order` int(3) DEFAULT NULL,
		PRIMARY KEY (`filter_id`)
		)
SQL;
		$this->db->query($q);
		
		$q=<<<SQL
		CREATE TABLE `{$db_prefix}tfm_filter_item` (
		`filter_item_id` int(5) NOT NULL AUTO_INCREMENT,
		`filter_id` int(3) NOT NULL,
		`title` text NOT NULL,
		`item_type` enum('a','ag','pf') NOT NULL,
		`item_id` int(11) DEFAULT NULL,
		`product_field` text,
		`multiple` tinyint(1) NOT NULL,
		`display` enum('list','select') NOT NULL,
		`range` text,
		`sort_order` int(5) DEFAULT NULL,
		PRIMARY KEY (`filter_item_id`)
		)
SQL;
		$this->db->query($q);
		
		$q=<<<SQL
		CREATE TABLE IF NOT EXISTS `{$db_prefix}tfm_setting` (
			`setting_key` varchar(20) NOT NULL,
			`setting_value` text NOT NULL,
			UNIQUE KEY `setting_key` (`setting_key`)
		)
SQL;
		$this->db->query($q);
	}
	
	public function dropModuleTables()
	{
		$this->db->query("DROP VIEW IF EXISTS `".DB_PREFIX."tfm_attribute`");
		$this->db->query("DROP TABLE IF EXISTS `".DB_PREFIX."tfm_filter`");
		$this->db->query("DROP TABLE IF EXISTS `".DB_PREFIX."tfm_filter_item`");
		$this->db->query("DROP TABLE IF EXISTS `".DB_PREFIX."tfm_setting`");
	}
	
	public function addLayout() {
		$this->db->query("INSERT INTO " . DB_PREFIX . "layout SET name = 'TFM Filtering Module'");
	
		$layout_id = $this->db->getLastId();
		$this->db->query("INSERT INTO `" . DB_PREFIX . "tfm_setting` VALUE('layout_id','{$layout_id}')");
		$this->db->query("INSERT INTO " . DB_PREFIX . "layout_route SET layout_id = '" . (int)$layout_id . "', store_id = '0', route = 'product/t_filter'");
	}
	
	public function removeLayout()
	{
		$id=self::getSetting('layout_id');
		$this->db->query("DELETE FROM " . DB_PREFIX . "layout WHERE `layout_id`='{$id}'");
		$this->db->query("DELETE FROM " . DB_PREFIX . "layout_route WHERE `layout_id`='{$id}'");
		$this->db->query("DELETE FROM `" . DB_PREFIX . "tfm_setting` WHERE `setting_key`='layout_id' AND `setting_value`='{$id}'");
	}
	
	public function getSetting($key)
	{
		$q="SELECT `setting_value` FROM `".DB_PREFIX."tfm_setting` WHERE `setting_key`='{$key}'";
		return $this->db->query($q)->rows[0]["setting_value"];
	}
	
	public function getStockStatus()
	{
		$q="SELECT * FROM `".DB_PREFIX."stock_status` WHERE language_id = '" . (int)$this->config->get('config_language_id') . "'";
		$query=$this->db->query($q);
		return $query->rows;
	}
	
	public function getFilters()
	{
		$q="SELECT * FROM `".DB_PREFIX."tfm_filter`";
		$query=$this->db->query($q);
		return $query->rows;
	}
	
	public function getFilterItems($filter_id)
	{
		$q="SELECT * FROM `".DB_PREFIX."tfm_filter_item` WHERE `filter_id`={$filter_id}";
		$query=$this->db->query($q);
		return $query->rows;
	}
	
	public function getAttributeGroups()
	{
		$q="SELECT `attribute_group_id` as 'id', `name` FROM `".DB_PREFIX."attribute_group_description` WHERE language_id = '" . (int)$this->config->get('config_language_id') . "'";
		$query=$this->db->query($q);
		return $query->rows;
	}
	
	public function getAttributes()
	{
		$q="SELECT `attribute_id` as 'id', `name` FROM `".DB_PREFIX."attribute_description` WHERE language_id = '" . (int)$this->config->get('config_language_id') . "'";
		$query=$this->db->query($q);
		return $query->rows;
	}
	
	public function getCategories()
	{
		$q="SELECT `category_id` as 'id', `name` FROM `".DB_PREFIX."category_description` WHERE language_id = '" . (int)$this->config->get('config_language_id') . "'";
		$query=$this->db->query($q);
		return $query->rows;
	}
	
	public function getManufacturers()
	{
		$q="SELECT `manufacturer_id` as 'id', `name` FROM `".DB_PREFIX."manufacturer`";
		$query=$this->db->query($q);
		return $query->rows;
	}
	
	public function getTfmAttributes($data = array()) {
	$sql = "SELECT * FROM `".DB_PREFIX."tfm_attribute` WHERE language_id = '" . (int)$this->config->get('config_language_id') . "'";

	if (!empty($data['filter_name'])) {
		$sql .= " AND LCASE(name) LIKE '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "%'";
	}

	if (!empty($data['filter_attribute_group_id'])) {
		$sql .= " AND attribute_group_id = '" . $this->db->escape($data['filter_attribute_group_id']) . "'";
	}

	$sort_data = array(
		'name',
		'attribute_group',
		'sort_order'
	);	

	if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
		$sql .= " ORDER BY " . $data['sort'];	 
	} else {
		$sql .= " ORDER BY attribute_group, name";	 
	}	 

	if (isset($data['order']) && ($data['order'] == 'DESC')) {
		$sql .= " DESC";
	} else {
		$sql .= " ASC";
	}

	if (isset($data['start']) || isset($data['limit'])) {
		if ($data['start'] < 0) {
			$data['start'] = 0;
		}				 

		if ($data['limit'] < 1) {
			$data['limit'] = 20;
		}	 

		$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
	}	 

	$query = $this->db->query($sql);

	return $query->rows;
	}	
}
?>